#include <head.h>

void Ls_l(const char * file_name)
{
    struct stat file_stat;
    struct passwd * u_name;
    struct group * g_name;
    stat(  file_name , &file_stat );

if (0==strcmp(".",file_name)||0==strcmp("..",file_name))
        {
            return ;
        }
    // 判定文件类型
    switch (file_stat.st_mode & S_IFMT) {  // 使用 S_IFMT 掩码获取文件类型
        case S_IFREG:
            printf("-");
            break;
        case S_IFDIR:
            printf("d");
            break;
        case S_IFCHR:
            printf("c");
            break;
        case S_IFBLK:
            printf("b");
            break;
        case S_IFIFO:
            printf("p");
            break;
        case S_IFLNK:
            printf("l");
            break;
        case S_IFSOCK:
            printf("s");
            break;
        default:
            printf("滚");
            break;
    }

    // 文件权限
    printf((file_stat.st_mode & S_IRUSR) ? "r" : "-");
    printf((file_stat.st_mode & S_IWUSR) ? "w" : "-");
    printf((file_stat.st_mode & S_IXUSR) ? "x" : "-");
    printf((file_stat.st_mode & S_IRGRP) ? "r" : "-");
    printf((file_stat.st_mode & S_IWGRP) ? "w" : "-");
    printf((file_stat.st_mode & S_IXGRP) ? "x" : "-");
    printf((file_stat.st_mode & S_IROTH) ? "r" : "-");
    printf((file_stat.st_mode & S_IWOTH) ? "w" : "-");
    printf((file_stat.st_mode & S_IXOTH) ? "x" : "-");

    // 链接数
    printf(" %d" , (int)file_stat.st_nlink);
    // 用户名
    u_name = getpwuid(file_stat.st_uid);
    printf(" %s" , u_name->pw_name);

    // 用户组名
    g_name = getgrgid(file_stat.st_gid);
    printf(" %s" , g_name->gr_name);

    // 文件大小   
    printf(" %d" , (int)file_stat.st_size);
    // 月份
    struct tm * file_tm = gmtime(&file_stat.st_mtime);
    printf(" %d月" , file_tm->tm_mon + 1);
    // 日
    printf(" %d" , file_tm->tm_mday);
    // 时:分
    printf(" %d:%d" , file_tm->tm_hour , file_tm->tm_min );
    // 文件名
    printf(" %s\n" , file_name);
}


int main(int argc, char const *argv[])
{
    DIR *dir = opendir("../../day02"); // 打开文件
    DIR_ERR(dir);

    struct dirent *dir_read; // 读取第一个目录
    struct dirent *dir_read1; //
    
    while ((dir_read = readdir(dir))!= NULL)
    {
        
        Ls_l(dir_read->d_name);
        // 再次读取下一目录
        // rewinddir(dir);  // 重置dir流
        // while ((dir_read1 = readdir(dir))!= NULL)
        // {
        //     Ls_l(dir_read->d_name);
        // }
        // printf("\t%s\n", dir_read->d_name);
    }
    return 0;
}


